import path from "path";
import fs from "fs";
import express from 'express';
import dotenv from 'dotenv';
import cors from 'cors';


dotenv.config({
  path: [
    path.resolve(process.cwd(), `.env.${process.env.NODE_ENV}`),
    path.resolve(process.cwd(), '.env'),
  ]
});

//初始化数据库
import { createPool } from "./util/db.js";
createPool();

const app = express();

app.use(cors());//可增加配置项，空白为默认值
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

//前台接口
import indexRoutes from './routes/index/index.js';
app.use(`/api/v1/index`, indexRoutes);

//后台接口
//登录接口
import loginRoutes from './routes/admin/login.js'
app.use('/api/v1/admin/user/login', loginRoutes);

import { auth } from './auth/auth.js'
import adminRoutes from './routes/admin/index.js';
app.use(`/api/v1/admin`, auth(), adminRoutes);

//处理路由器不存在的其他地址
app.use(function (req, res, next) {// 处理 JWT 认证错误

  res.send({
    code: 404,
    msg: `${req.path} 地址不存在`
  })
});


import { MulterError } from "multer";
//统一处理服务器错误
app.use(function (err, req, res, next) {
  //处理特殊错误，文件上传的工具函数的错误，token验证失败的错误......
  if (err instanceof MulterError) {
    res.send({
      code: 400,
      msg: "文件上传错误:" + err.message
    })
    return;
  }
  if (err.name === 'UnauthorizedError') {
    res.status(401).send({
      code: 401,
      msg: '未授权访问，请提供有效的访问令牌'
    });
    return;
  }

  if (process.env.NODE_ENV == "development") {
    console.log(err);
  } else {
    let logPath = path.resolve(process.cwd(), `./logs/${new Date().getTime()}.log`);
    let info = new Date().toLocaleString() + "\n" + decodeURI(err.stack);
    fs.writeFileSync(logPath, info)
  }
  res.send({
    code: 500,
    msg: "服务器运行错误，请联系管理员"
  })
});

const PORT = process.env.PORT ?? 8000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

export default app;
